package cn.wildfire.chat.kit;

import android.app.Activity;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.google.android.material.appbar.AppBarLayout;
import com.sourcemuch.im.caiba.CaiBaChatApp;
import com.sourcemuch.im.caiba.ManumotiveIBinder;
import com.sourcemuch.im.caiba.R;import com.sourcemuch.im.caiba.R2;
import com.sourcemuch.im.caiba.R2;

import androidx.annotation.LayoutRes;
import androidx.annotation.MenuRes;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.AppCompatImageButton;
import androidx.appcompat.widget.AppCompatTextView;
import androidx.appcompat.widget.Toolbar;
import butterknife.BindView;
import butterknife.ButterKnife;
import cn.wildfire.chat.app.extendsion.classes.Textual;
import cn.wildfire.chat.app.extendsion.utils.StatusBarUtil;
import cn.wildfire.chat.app.extendsion.utils.TextUtils;
import cn.wildfire.chat.app.main.MainActivity;
import cn.wildfire.chat.kit.contact.newfriend.SearchUserActivity;

/**
 * Create by HEKE, 2019/8/20 10:44
 * TODO 界面基类
 */
public abstract class WfcBaseActivity extends AppCompatActivity {

    @BindView(R2.id.appbar)
    public AppBarLayout appbar;
    @BindView(R2.id.toolbar)
    public Toolbar toolbar;

    /**
     * 搜索栏
     */
    LinearLayout searchLayout;
    TextView searchTitleView;

    /**
    /**
     * 界面右上角按钮菜单
     */
    protected Menu mMenu;
    public int type = Textual.TYPE_CONVERSATION;

    /**
     * modify by HEKE , 2019/8/20 20:43
     * TODO 信推程序
     */
    public CaiBaChatApp caiBaChatApp;
    public ManumotiveIBinder manumotiveIBinder;
    public Handler mHandler;

    /**
     * 替代Toolbar显示控件
     */
    protected RelativeLayout replaceViewsLayout;
    protected ImageView backIcon;
    protected ImageView moreIcon;
    protected TextView titleView;
    protected TextView rightTxtView;
    protected boolean activityContainsReplaceViews;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        try {
            this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
            beforeViews();
            setContentView(contentLayout());
            ButterKnife.bind(this);
            caiBaChatApp = (CaiBaChatApp) getApplicationContext();
            manumotiveIBinder = caiBaChatApp.manumotiveIBinder;
            mHandler = CaiBaChatApp.getMainHandler();
            setSupportActionBar(toolbar);
            initReplaceViews();
            if (showHomeMenuItem()) {
                getSupportActionBar().setDisplayHomeAsUpEnabled(true);
            }
            afterViews();
            setTitleCenterThenSetSearchView();
        } catch (Exception e) {
        }
    }

    /**
     * 装在替代顶部控件
     */
    private void initReplaceViews() {
        replaceViewsLayout = findViewById(R.id.replaceViewsLayout);
        if (replaceViewsLayout != null) {
            activityContainsReplaceViews = true;
            backIcon = findViewById(R.id.backIcon);
            moreIcon = findViewById(R.id.moreIcon);
            titleView = findViewById(R.id.titleView);
            rightTxtView = findViewById(R.id.rightTxtView);
            backIcon.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    onBackPressed();
                }
            });
            moreIcon.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    if (type == Textual.TYPE_CONTACT) {
                        toSearchUser();
                    } else {
                        replaceMoreClicked();
                    }
                }
            });
        }
    }

    /**
     * 获取替代主题空间主布局
     */
    public RelativeLayout getReplaceViewsLayout() {
        return replaceViewsLayout;
    }

    /**
     * 获取搜索控件
     */
    public LinearLayout getSearchLayout() {
        return searchLayout;
    }

    /**
     * 判断当前界面是否使用替代标题栏
     */
    public boolean isActivityContainsReplaceViews() {
        return activityContainsReplaceViews;
    }

    /**
     * 替代控件更多方案点击
     */
    public void replaceMoreClicked() {
    }

    /**
     * 设置是否替换之前的 Toolbar 内容标记
     *
     * @param userReplaceViews 是否使用替代控件
     * @param type             -1表示只需要标题，0为只需要标题与右上角更多按钮，1为返回标题更多都需求,2为只需要返回和标题,3 标题居左显示
     */
    public void setToolbarOrReplaceType(boolean userReplaceViews, int type) {
        if (userReplaceViews) {
            if (isActivityContainsReplaceViews()) {
                toolbar.setVisibility(View.GONE);
                appbar.setVisibility(View.GONE);
                replaceViewsLayout.setVisibility(View.VISIBLE);
                switch (type) {
                    case -1:
                        backIcon.setVisibility(View.GONE);
                        moreIcon.setVisibility(View.GONE);
                        rightTxtView.setVisibility(View.GONE);
                        titleView.setVisibility(View.VISIBLE);
                        break;
                    case 0:
                        backIcon.setVisibility(View.GONE);
                        rightTxtView.setVisibility(View.GONE);
                        moreIcon.setVisibility(View.VISIBLE);
                        titleView.setVisibility(View.VISIBLE);
                        break;
                    case 1:
                        backIcon.setVisibility(View.VISIBLE);
                        moreIcon.setVisibility(View.VISIBLE);
                        titleView.setVisibility(View.VISIBLE);
                        rightTxtView.setVisibility(View.GONE);
                        break;
                    case 2:
                        backIcon.setVisibility(View.VISIBLE);
                        moreIcon.setVisibility(View.GONE);
                        titleView.setVisibility(View.VISIBLE);
                        rightTxtView.setVisibility(View.GONE);
                        break;
                    case 3:
                        backIcon.setVisibility(View.VISIBLE);
                        moreIcon.setVisibility(View.GONE);
                        titleView.setVisibility(View.VISIBLE);
                        rightTxtView.setVisibility(View.GONE);
                        // 居左显示设置，新版UI20190918，限制要求为默认居中显示，此处暂时屏蔽，仅供参考修改
                        /*RelativeLayout.LayoutParams rl = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT,
                                RelativeLayout.LayoutParams.MATCH_PARENT);
                        rl.setMargins(getResources().getDimensionPixelSize(R.dimen.y50), 0, 0, 0);
                        rl.addRule(RelativeLayout.ALIGN_RIGHT | RelativeLayout.CENTER_VERTICAL, R2.id.backIcon);
                        titleView.setLayoutParams(rl);*/
                        break;
                    default:
                        break;
                }
            }
        } else {
            if (isActivityContainsReplaceViews()) {
                toolbar.setVisibility(View.VISIBLE);
                replaceViewsLayout.setVisibility(View.GONE);
            }
        }
    }

    /**
     * 设置文本及绑定点击事件
     *
     * @param visiable
     * @param content
     * @param onClickListener
     */
    public void setTextThenBinClickForRightTextView(int visiable, String content, View.OnClickListener onClickListener) {
        if (rightTxtView == null) {
            return;
        }
        rightTxtView.setVisibility(visiable);
        rightTxtView.setText(content);
        rightTxtView.setOnClickListener(onClickListener);
        ViewGroup.LayoutParams layoutParams = getRightTxtView().getLayoutParams();
        if (content.equals(getString(R.string.next_title))) {
            layoutParams.width = getResources().getDimensionPixelSize(R.dimen.y150);
        } else {
            layoutParams.width = getResources().getDimensionPixelSize(R.dimen.y100);
        }
        layoutParams.height = getResources().getDimensionPixelSize(R.dimen.y60);
        rightTxtView.setLayoutParams(layoutParams);
    }

    /**
     * 设置右上角更多图标显示及点击事件
     */
    public void setMoreButtonThenBindClickForRightButtonView(int visiable, int resId, View.OnClickListener onClickListener) {
        if (moreIcon == null) {
            return;
        }
        moreIcon.setVisibility(visiable);
        moreIcon.setImageResource(resId);
        moreIcon.setOnClickListener(onClickListener);
    }

    /**
     * 当选择右上角文本显示样式时，获取控件对象
     */
    public TextView getRightTxtView() {
        return rightTxtView;
    }

    /**
     * 获取标题控件
     */
    public TextView getTitleView() {
        return titleView;
    }

    /**
     * 设置替代方案标题
     *
     * @param value 为空时，使用id
     * @param id    为-1时，使用value
     * @return
     */
    public String setReplaceTitle(String value, int id) {
        if (!isActivityContainsReplaceViews()) {
            return "";
        }
        if (!TextUtils.isTextEmpty(value) && value.length() >= 15) {
            value = value.substring(0, 14) + "等";
        }
        if (value != null) {
            titleView.setText(value);
        }
        if (id > 0 && id != -1) {
            titleView.setText(id);
            value = titleView.getText().toString();
        }
        return value;
    }

    /**
     * modify by HEKE , 2019/8/28 17:43 TODO 粗暴的方法设置ToolBar控件标题无法居中显示问题
     */
    protected void setTitleCenterThenSetSearchView() {
        try {
            // 遍历查询toolbar中的所有子控件
            if (toolbar != null) {
                int size = toolbar.getChildCount();
                for (int i = 0; i < size; i++) {
                    View view = toolbar.getChildAt(i);
                    if (view instanceof AppCompatImageButton) {
                        AppCompatImageButton back = (AppCompatImageButton) view;
                        back.setImageResource(R.mipmap.bt_fanhui);
                    } else if (view instanceof AppCompatTextView) {
                        TextView title = (TextView) view;
                        ViewGroup.LayoutParams layoutParams = title.getLayoutParams();
                        layoutParams.width = ViewGroup.LayoutParams.MATCH_PARENT;
                        layoutParams.height = ViewGroup.LayoutParams.MATCH_PARENT;
                        title.setLayoutParams(layoutParams);
                        title.setGravity(Gravity.CENTER);
                    }
                }
            }
            // 初始化搜索栏
            searchLayout = getWindow().getDecorView().findViewById(R.id.searchLayout);
            searchTitleView = getWindow().getDecorView().findViewById(R.id.searchTitle);
            if (searchLayout != null) {
                searchLayout.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        onSearChLayoutClick();
                    }
                });
                /**
                 * 如果不是主界面，自动隐藏搜索栏
                 * */
                if (!(this instanceof MainActivity)) {
                    setSearchLayoutVisibility(false);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        if (menu() != 0) {
            getMenuInflater().inflate(menu(), menu);
        }
        afterMenus(menu);
        mMenu = menu;
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int itemId = item.getItemId();
        if (itemId == android.R.id.home) {
            hideInputMethod();
            onBackPressed();
            return true;
        } else if (itemId == R.id.more) {
            moreMenuSet();
        }
        return super.onOptionsItemSelected(item);
    }

    /**
     * modify by HEKE , 2019/8/28 22:36 TODO 更多按钮设置
     */
    private void moreMenuSet() {
        MenuItem more = mMenu.findItem(R.id.more);
        if (more == null) {
            return;
        }
        if (type == Textual.TYPE_CONVERSATION) {
            setMenuItemVisibility(R.id.chat, true);
            setMenuItemVisibility(R.id.add_contact, true);
            setMenuItemVisibility(R.id.scan_qrcode, true);
        } else if (type == Textual.TYPE_CONTACT) {
            setMenuItemVisibility(R.id.chat, false);
            setMenuItemVisibility(R.id.add_contact, false);
            setMenuItemVisibility(R.id.scan_qrcode, false);
            toSearchUser();
        }
    }

    /**
     * 跳转至联系人搜索界面
     */
    private void toSearchUser() {
        Intent intent = new Intent(this, SearchUserActivity.class);
        intent.putExtra("search_type", SearchUserActivity.TYPE_USER_SEARCH);
        startActivity(intent);
    }

    protected void hideInputMethod() {
        InputMethodManager imm = (InputMethodManager) this.getSystemService(Activity.INPUT_METHOD_SERVICE);
        View view = getCurrentFocus();
        if (view != null) {
            imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
        }
    }

    /**
     * modify by HEKE , 2019/8/28 17:03 TODO 不同的模块不同的主题栏显示
     */
    public void setShowIndex(int index) {
        type = index;
        switch (index) {
            case Textual.TYPE_CONVERSATION:
                // 会话
                searchLayout.setVisibility(View.VISIBLE);
                replaceViewsLayout.setBackgroundColor(getResources().getColor(R.color.colorPrimary));
                toolbar.setTitle(getString(R.string.message_title));
                setMenuItemVisibility(R.id.more, true);
                setMenuItemIcon(R.id.more, R.mipmap.button_tanchu1);
                if (isActivityContainsReplaceViews()) {
                    titleView.setText(getString(R.string.message_title));
                    setToolbarOrReplaceType(true, 0);
                    moreIcon.setImageResource(R.mipmap.button_tanchu1);
                }
                break;
            case Textual.TYPE_CONTACT:
                // 联系人
                searchLayout.setVisibility(View.VISIBLE);
                replaceViewsLayout.setBackgroundColor(getResources().getColor(R.color.colorPrimary));
                toolbar.setTitle(getString(R.string.contact_title));
                setMenuItemVisibility(R.id.more, true);
                setMenuItemIcon(R.id.more, R.mipmap.button_addnewfriend);
                if (isActivityContainsReplaceViews()) {
                    titleView.setText(getString(R.string.contact_title));
                    setToolbarOrReplaceType(true, -1);
                    moreIcon.setImageResource(R.mipmap.button_addnewfriend);
                }
                break;
            case Textual.TYPE_GROUP_CONVERSATION:
                // 群组
                searchLayout.setVisibility(View.VISIBLE);
                replaceViewsLayout.setBackgroundColor(getResources().getColor(R.color.colorPrimary));
                toolbar.setTitle(getString(R.string.qunzu_title));
                setMenuItemVisibility(R.id.more, false);
                if (isActivityContainsReplaceViews()) {
                    titleView.setText(getString(R.string.qunzu_title));
                    setToolbarOrReplaceType(true, -1);
                }
                break;
            case Textual.TYPE_ME:
                // 我的
                searchLayout.setVisibility(View.GONE);
                replaceViewsLayout.setBackgroundColor(getResources().getColor(R.color.white));
                toolbar.setTitle(getString(R.string.person_center_title));
                setMenuItemVisibility(R.id.more, false);
                if (isActivityContainsReplaceViews()) {
                    titleView.setText(getString(R.string.person_center_title));
                    setToolbarOrReplaceType(true, -1);
                }
                break;
            default:
                break;
        }
    }

    /**
     * 设置菜单栏子控件显示或隐藏
     *
     * @param id
     * @param visiable
     */
    private void setMenuItemVisibility(int id, boolean visiable) {
        if (mMenu == null) {
            return;
        }
        MenuItem menuItem = mMenu.findItem(id);
        if (menuItem != null) {
            menuItem.setVisible(visiable);
            menuItem.setEnabled(visiable);
        }
    }

    /**
     * 设置菜单子控件的图标
     */
    public void setMenuItemIcon(int id, int iconId) {
        if (mMenu == null) {
            return;
        }
        MenuItem menuItem = mMenu.findItem(id);
        menuItem.setIcon(iconId);
    }

    /**
     * @return 布局文件
     */
    protected abstract @LayoutRes
    int contentLayout();

    /**
     * @return menu
     */
    protected @MenuRes
    int menu() {
        return 0;
    }

    /**
     * {@link AppCompatActivity#setContentView(int)}之前调用
     */
    protected void beforeViews() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            int color = getResources().getColor(R.color.colorPrimary);
            getWindow().setNavigationBarColor(Color.TRANSPARENT);
            getWindow().setStatusBarColor(color);
            StatusBarUtil.setStatusTextColor(true, this);
        }
        try {
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED //锁屏状态下显示
                    | WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD //解锁
                    | WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON //保持屏幕长亮
                    | WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON); //打开屏幕
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * {@link AppCompatActivity#setContentView(int)}之后调用
     * <p>
     * 此时已经调用了{@link ButterKnife#bind(Activity)}, 子类里面不需要再次调用
     */
    protected void afterViews() {
    }

    /**
     * {@code getMenuInflater().inflate(menu(), menu);}之后调用
     *
     * @param menu
     */
    protected void afterMenus(Menu menu) {
    }

    @Override
    protected void onResume() {
        super.onResume();
        /**
         * modify by HEKE , 2019/8/21 14:05
         * TODO 程序在前台时，隐藏窗口
         */
        if (caiBaChatApp != null && caiBaChatApp.lightThenNotifyPhone != null) {
            caiBaChatApp.lightThenNotifyPhone.hideWindow();
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        hideInputMethod();
    }

    /**
     * modify by HEKE , 2019/8/28 18:13 TODO 搜索控件被点击
     */
    protected void onSearChLayoutClick() {
    }

    /**
     * 设置搜索栏显示或隐藏
     *
     * @param visiable
     */
    public void setSearchLayoutVisibility(boolean visiable) {
        if (searchLayout == null) {
            return;
        }
        searchLayout.setVisibility(visiable ? View.VISIBLE : View.GONE);
    }

    /**
     * 设置搜索栏内容
     *
     * @param title
     */
    public void setSearchTitle(String title) {
        if (searchTitleView == null) {
            return;
        }
        searchTitleView.setText("" + title);
    }

    protected boolean showHomeMenuItem() {
        return true;
    }

    public boolean checkPermission(String[] permissions) {
        boolean granted = true;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            for (String permission : permissions) {
                granted = checkSelfPermission(permission) == PackageManager.PERMISSION_GRANTED;
                if (!granted) {
                    break;
                }
            }
        }
        return granted;
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        /**
         * modify by HEKE , 2019/8/20 10:43
         * TODO 非主界面返回按键为返回上一个界面
         */
        if (event.getKeyCode() == KeyEvent.KEYCODE_BACK) {
            if (this instanceof MainActivity) {
                moveTaskToBack(true);
            } else {
                onBackPressed();
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

}
